package pri.hillchen.std.netty.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 15:57 2018/3/30 0030.
 */
public class AioTimeServerHandler implements Runnable {
    public static final String QUERY_TIME_COMMAND = "CURRENT_TIME";
    private int port;
    private CountDownLatch latch;
    private AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AioTimeServerHandler(int port) throws IOException {
        this.port = port;
        asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
        asynchronousServerSocketChannel.bind(new InetSocketAddress(port));

        System.out.println("time server is start in port:" + port);
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private void doAccept(){
        asynchronousServerSocketChannel.accept(this, new CompletionHandler<AsynchronousSocketChannel, AioTimeServerHandler>() {
            @Override
            public void completed(AsynchronousSocketChannel result, AioTimeServerHandler attachment) {

                attachment.asynchronousServerSocketChannel.accept(attachment,this);
                ByteBuffer bb = ByteBuffer.allocate(1024);
                result.read(bb, bb, new ReadCompletionHandler(result));

            }

            @Override
            public void failed(Throwable exc, AioTimeServerHandler attachment) {
                exc.printStackTrace();
                attachment.latch.countDown();
            }
        });
    }


}
